import express from 'express';
import path from 'path';
import chalk from 'chalk';
import {FileInfo} from '../types';
import {exec} from 'child_process';
import {globalConfig} from '../config';
import {ProjectService} from "./ProjectService";
import {FileService} from "./FileService";
import {CleanupService} from "./CleanupService";
import {SystemService} from "./SystemService";

/**
 * 启动服务器
 */
export function startServer(): void {
  const config = globalConfig.config;
  const app = express();
  const server = app.listen(config.server.port, () => {
    const url = `http://localhost:${config.server.port}`;
    console.log(chalk.green(`服务器已启动: ${url}`));

    // 自动打开浏览器
    // openBrowser(url);
  });

  // 设置静态资源目录
  app.use(express.static(path.join(__dirname, '../public')));
  app.use(express.json());

  // 文件树缓存
  let fileTreeCache: FileInfo | null = null;

  // API 路由
  // 获取基础信息（极速启动时使用）
  app.post('/api/basic', async (req, res) => {
    try {
      // 返回基本目录信息
      const basicInfo = {
        rootPath: config.scan.targetDir,
        rootName: path.basename(config.scan.targetDir),
        timestamp: Date.now()
      };
      res.json(basicInfo);
    } catch (error) {
      console.error('获取基本信息失败:', error);
      res.status(500).json({error: `服务器错误: ${(error as Error).message}`});
    }
  });

  // 项目路由
  ProjectService(app);
  // 文件路由
  FileService(app);
  // 清理路由
  CleanupService(app);
  // 系统路由
  SystemService(app);

  // 处理所有其他请求，返回主页
  app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, '../public/index.html'));
  });

  // 优雅地处理进程终止
  process.on('SIGINT', () => {
    console.log(chalk.yellow('\n正在关闭服务器...'));
    server.close(() => {
      console.log(chalk.green('服务器已关闭'));
      process.exit(0);
    });
  });
}

/**
 * 打开浏览器
 */
function openBrowser(url: string): void {
  const command = process.platform === 'win32' ? 'start' :
    process.platform === 'darwin' ? 'open' : 'xdg-open';

  exec(`${command} ${url}`, (error) => {
    if (error) {
      console.log(chalk.red(`无法打开浏览器: ${error.message}`));
    }
  });

  console.log(chalk.green(`已尝试在浏览器中打开: ${url}`));
}
